//
//  KKChatDetailViewController.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/21.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKChatDetailViewController.h"

#import "KKMessageItem.h"
#import "KKNetworkRequest+V1.h"
#import "KKConversationManager.h"
#import "KKImagePickerManager.h"
#import "KKTopAlertView.h"

@interface KKChatDetailViewController ()

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *bottomHeight;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *bottomSpace;

@property (nonatomic, strong) UILabel *lab_other;

@end

@implementation KKChatDetailViewController

- (void)loadView {
    [super loadView];
    
    [self private_initViewUI];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.navigationItem.title = self.conversationItem.kk_customer.nick;
    
    {
        UIView *topView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 120, 44)];
        UILabel *lab_nickName = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(topView.bounds), 22)];
        lab_nickName.textAlignment = NSTextAlignmentCenter;
        lab_nickName.font = [UIFont boldSystemFontOfSize: 17];
        lab_nickName.textColor = [UIColor colorWithHexString: @"3D5372"];
        lab_nickName.text = self.conversationItem.kk_customer.nick;
        [topView addSubview: lab_nickName];
        UILabel *lab_other = [[UILabel alloc] initWithFrame: CGRectMake(0, 22, CGRectGetWidth(topView.bounds), 22)];
        lab_other.textAlignment = NSTextAlignmentCenter;
        lab_other.font = [UIFont systemFontOfSize: 12];
        lab_other.textColor = [UIColor colorWithHexString: @"3D5372"];
        lab_other.text = @"";
        [topView addSubview: lab_other];
        self.navigationItem.titleView = topView;
        self.lab_other = lab_other;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(private_listenKeyboard:) name: UIKeyboardWillShowNotification object: nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(private_listenKeyboard:) name: UIKeyboardWillHideNotification object: nil];
    
    [self configBaseInfo];
    
    [self private_loadingHistoryMessageItems];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
    
    KKConversationManager.defaultManager.currentItem = self.conversationItem;
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear: animated];
    
    KKConversationManager.defaultManager.currentItem = nil;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    NSLog(@"KKChatDetailViewController");
}

#pragma mark -

- (void)configBaseInfo {
    
//    self.tableView.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"background_normal"]];
    self.tableView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: @"background_normal"]];
    
    self.arr_msgItems = self.conversationItem.msgList;
    
    __weak typeof(self) weakSelf = self;
    self.conversationItem.receiveMsgHandle = ^(NSArray * _Nonnull msgList) {
        
        BOOL scroll = weakSelf.tableView.contentSize.height - weakSelf.tableView.contentOffset.y - CGRectGetHeight(weakSelf.tableView.bounds) < 30 ? true : false;
        [weakSelf private_showMessageTableViewUIWithMsgs: msgList scroll: scroll];
    };
}


- (void)private_initViewUI{
    
//    UIImageView *bgImageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"background_normal"]];
//    self.tableView.backgroundView = bgImageView;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    UITapGestureRecognizer *tapper = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(on_Tap:)];
    [self.tableView addGestureRecognizer: tapper];
    
    __weak typeof(self) weakSelf = self;
    //  开始编辑
    self.textView.didBeginEditTextHandle = ^{
        NSLog(@"开始进行编辑内容");
        weakSelf.lab_tips.hidden = true;
    };
    //  高度改变
    self.textView.changeContentHeightHandle = ^(CGFloat height) {
        [weakSelf private_updateBottomViewUIWithHeight: height];
    };
    //  结束编辑
    self.textView.didEndEditTextHandle = ^(NSString * _Nonnull text) {
        if (text.length > 0) {
            [weakSelf private_sendMessageToOther: text];
        }
        else {
            weakSelf.lab_tips.hidden = false;
        }
    };
}

- (void)private_listenKeyboard:(NSNotification*)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    CGRect endFrame = [[userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double duration = [[userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey] boolValue];
    
    __weak typeof(self) weakSelf = self;
    
    CGFloat constant = CGRectGetMinY(endFrame) - SCREEN_HEIGHT;
    if (@available(iOS 11.0, *)){
        UIWindow *window = [[UIApplication sharedApplication] delegate].window;
        if (window.safeAreaInsets.bottom > 0.0 && constant != 0.0) {
            constant += window.safeAreaInsets.bottom;
        }
    }
    
    [UIView animateWithDuration: duration animations:^{
        weakSelf.bottomSpace.constant = constant;
    } completion:^(BOOL finished) {
        [weakSelf.view layoutIfNeeded];
        if (self.arr_msgItems.count) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MAX(0, self.arr_msgItems.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated: true];
        }
    }];
}

#pragma mark - Private methods
- (void)private_updateBottomViewUIWithHeight:(CGFloat)height {
    //  更新bottomView的高度
    //  bottomView的默认高度为94
    
    CGFloat updateHeight = height + 20;
    if (updateHeight > 110) {
        updateHeight = 115;
    }
    else if(updateHeight < 54){
        updateHeight = 54;
    }
    else {
        updateHeight += 7;
    }
    
    self.bottomHeight.constant = updateHeight;
    [self.bottomView layoutIfNeeded];
}

- (void)private_loadingHistoryMessageItems {
    //  获取会话中的历史消息
    __weak typeof(self) weakSelf = self;
    
    KKNetworkRequest *request = [KKNetworkRequest request_getChatItemDetail: self.conversationItem.identifier];
    [KKNetworking sendRequest: request responseCallBack:^(id response, NSString *error) {
        
        if ([response isKindOfClass: [NSDictionary class]]) {
            NSDictionary *tmpDictionary = (NSDictionary*)response;
            NSArray *tmpArray = tmpDictionary[@"messages"];
            
            NSString *notes = tmpDictionary[@"notes"];
            weakSelf.lab_other.text = notes;
            
            NSMutableArray *arr_tmp = [NSMutableArray array];
            for (NSDictionary *tmpItem in tmpArray) {
                RAMessage *item = [RAMessage itemWithJson: tmpItem];
                [arr_tmp addObject: item];
            }
            [weakSelf.conversationItem loadHistoryMessages: arr_tmp];
        }
        weakSelf.arr_msgItems = weakSelf.conversationItem.msgList;
        [weakSelf.tableView reloadData];
        
        [weakSelf private_updateHistoryMessageTableViewUIWithMsgs: weakSelf.arr_msgItems scrollToBottom: true];
    }];
}

#pragma mark -

- (void)private_sendMessageToOther:(NSString*)content {
    //  发送消息给对方

    RASender *sender = [RASender new];
    sender.identifier = [KKUser uid];
    sender.headimg = [KKUser defaultUser].headimg;
    sender.nick = [KKUser defaultUser].nickName;
    
    RATextMessage *message = [RATextMessage messageWithText: content sender: sender];
    KKMessageItem *msg = [KKMessageItem msgWithTMessage: message];
    
    __weak typeof(self) weakSelf = self;
    NSArray *msgList = [self.conversationItem sendMessage: msg succ:^(NSArray * _Nonnull msgList) {
    } fail: ^(NSInteger code, NSString * _Nonnull msg) {
        [weakSelf kk_showTopAlertViewWithMessage: msg];
    }];
    
    BOOL scroll = self.tableView.contentSize.height - self.tableView.contentOffset.y - CGRectGetHeight(self.tableView.bounds) < 30 ? true : false;
    [self private_showMessageTableViewUIWithMsgs: msgList scroll: scroll];
}

- (void)private_sendImageToOther:(UIImage*)image {
    //  发送图片消息给对方
    RASender *sender = [RASender new];
    sender.identifier = [KKUser uid];
    sender.headimg = [KKUser defaultUser].headimg;
    sender.nick = [KKUser defaultUser].nickName;
    RAImageMessage *message = [RAImageMessage messageWithImage: image sender: sender];
    KKMessageItem *msg = [KKMessageItem msgWithTMessage: message];
    
    __weak typeof(self) weakSelf = self;
    NSArray *msgList = [self.conversationItem sendImageMessage: msg succ:^(NSArray * _Nonnull msgList) {
        
    } fail:^(NSInteger code, NSString * _Nonnull msg) {
        [weakSelf kk_showTopAlertViewWithMessage: msg];
    }];
    
    BOOL scroll = self.tableView.contentSize.height - self.tableView.contentOffset.y - CGRectGetHeight(self.tableView.bounds) < 30 ? true : false;
    [self private_showMessageTableViewUIWithMsgs: msgList scroll: scroll];
}

#pragma mark -

- (void)private_showMessageTableViewUIWithMsgs:(NSArray*)msgs scroll:(BOOL)scroll{
    
    if (msgs.count == 0) {
        return;
    }
    
    if (_arr_msgItems.count == 1) {
        [self.tableView reloadData];
    }
    else {
        
        [self.tableView beginUpdates];
        NSMutableArray *indexPaths = [NSMutableArray array];
        for (KKMessageItem *msg in msgs) {
            NSInteger index = [_arr_msgItems indexOfObject: msg];
            [indexPaths addObject: [NSIndexPath indexPathForRow: index inSection:0]];
        }
        [self.tableView insertRowsAtIndexPaths: indexPaths withRowAnimation: UITableViewRowAnimationNone];
        [self.tableView endUpdates];
        
        if (scroll) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSIndexPath *updateIndexPath = [NSIndexPath indexPathForRow: self->_arr_msgItems.count - 1 inSection: 0];
                [self.tableView scrollToRowAtIndexPath: updateIndexPath atScrollPosition: UITableViewScrollPositionNone animated: YES];
            });
        }
    }
}

//  获取历史消息，更新ui
- (void)private_updateHistoryMessageTableViewUIWithMsgs:(NSArray*)msgs scrollToBottom:(BOOL)scroll{
    
    __weak typeof(self) weakSelf = self;
    if (msgs.count > 0) {
        if (scroll) {
            NSIndexPath *last = [NSIndexPath indexPathForRow:_arr_msgItems.count-1 inSection:0];
            [weakSelf.tableView scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionBottom animated: NO];
        }
        else {
            NSIndexPath *last = [NSIndexPath indexPathForRow:msgs.count inSection:0];
            [weakSelf.tableView scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionTop animated: false];
        }
    }
}

#pragma mark - Action methods

- (IBAction)action_camera:(id)sender {
    //  相机
    
    __weak typeof(self) weakSelf = self;
    KKImagePickerManager *manager = [KKImagePickerManager kk_defaultManager];
    manager.maxLimit = 1;
    manager.resultBlock = ^(NSArray *images) {
        [weakSelf private_sendImageToOther: images.firstObject];
    };
    [manager kk_takePicture];
}

- (void)on_Tap:(UITapGestureRecognizer*)tapper {
    
    if (self.textView.isFirstResponder) {
        [self.textView resignFirstResponder];
    }
}

@end
